package groovy.model

import groovy.database.Util;
import groovy.json.internal.Exceptions;
import groovy.sql.*
import groovy.tools.Tools;

import javax.servlet.http.HttpServletRequest;

class User {
	
	String id, account, password, acceptpassword, job, birthday, gender, interest, introduce
	
	static User fromRequest(HttpServletRequest req) {
		new User(req.getParameterMap().inject([:]) { c, k, v -> 
			if(v.size() == 1) c[k] = v[0] else c[k] = v.join(", ") 
			c
		})
	}
	
	def User pull() {
		User ret = null
		Util.execute { Sql db ->
			def row = db.firstRow("select * from user where account = :account and password = :password", 
				[ account: account, password: password ]) as GroovyRowResult
			if(row == null) return
			ret = new User(row.keySet().inject([:]) { c, e -> c[e] = row[e]; c })
		}
		ret
	}
	
	def save() {
		Tools.PrintIfHasException {
			Util.execute { Sql db ->
				db.executeInsert("""
				insert into user(gender, birthday, job, interest, introduce, account, password)
					values(?,?,?,?,?,?,?)
			""", [ gender, birthday, job, interest, introduce, account, password ])
			}
		}
	}
	
	static main(def args) {

	}
}
